package com.tpc.yaoxpt.service;


import com.tpc.yaoxpt.main.LogModule;
import com.tpc.yaoxpt.main.MainController;
import com.tpc.yaoxpt.utils.FileUtil;
import com.tpc.yaoxpt.utils.StringUtil;
import javafx.application.Platform;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;

public class SignService {

    final LogModule logModule = new LogModule();

    public String getSign(String timestamp){
        try {
            Map<String, String> ptConfig = FileUtil.getPTConfig();
            String apiKey = ptConfig.get("APIKEY");
            String secretKey = ptConfig.get("SECRETKEY");
            String input = "ApiKey=" + apiKey + "&secretKey=" + secretKey + "&Timestamp=" + timestamp;
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(input.getBytes());
            byte[] digest = md.digest();

            // 转换为十六进制
            StringBuilder hexString = new StringBuilder();
            for (byte b : digest) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) hexString.append('0');
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (IOException | NoSuchAlgorithmException e) {
//            logModule.appendLogInfo(logModule.getLogInfo() + "\n" + e.getMessage());
            Platform.runLater(new Runnable() {
                @Override
                public void run() {
                    MainController.staticLogText.appendText("\n" + e.getMessage());
                }
            });
            throw new RuntimeException(e);
        }
    }
}
